﻿
//
// 版权所有 (c) 2021-2023 JR
//
// 特此免费授予获得本软件的任何人以处理本软件的权利，但须遵守以下条件：在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
//
// 软件按“原样”提供，不提供任何形式的明示或暗示的保证，包括但不限于对适销性、适用性和非侵权的保证。
// 在任何情况下，作者或版权持有人均不对任何索赔、损害或其他责任负责，无论是因合同、侵权或其他方式引起的，与软件或其使用或其他交易有关。

using System.Reflection;
using static SKIT.FlurlHttpClient.Wechat.Api.Events.TransferCustomerServiceReply.Types;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.ComponentTCBDescribeCloudBaseRunEnvironmentsResponse.Types.Environment.Types;

namespace EMC.VISITOR.Core.Service;

/// <summary>
/// 系统数据库管理服务
/// </summary>
[ApiDescriptionSettings( Order = 100)]
public class SysDatabaseService : IDynamicApiController, ITransient
{
    private readonly ISqlSugarClient _db;
    private readonly IViewEngine _viewEngine;
    private readonly CodeGenOptions _codeGenOptions;

    public SysDatabaseService(ISqlSugarClient db,
        IViewEngine viewEngine,
        IOptions<CodeGenOptions> codeGenOptions)
    {
        _db = db;
        _viewEngine = viewEngine;
        _codeGenOptions = codeGenOptions.Value;
    }

    /// <summary>
    /// 获取库列表
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取库列表")]
    public List<dynamic> GetList()
    {
        return App.GetOptions<DbConnectionOptions>().ConnectionConfigs.Select(u => u.ConfigId).ToList();
    }

    /// <summary>
    /// 获取字段列表
    /// </summary>
    /// <param name="tableName">表名</param>
    /// <param name="configId">ConfigId</param>
    /// <returns></returns>
    [AllowAnonymous]
    [DisplayName("获取字段列表")]
    public List<DbColumnOutput> GetColumnList(string tableName, string configId = SqlSugarConst.MainConfigId)
    {
        var db = _db.AsTenant().GetConnectionScope(configId);
        if (string.IsNullOrWhiteSpace(tableName))
            return new List<DbColumnOutput>();

        return db.DbMaintenance.GetColumnInfosByTableName(tableName, false).Adapt<List<DbColumnOutput>>();
    }

    /// <summary>
    /// 增加列
    /// </summary>
    /// <param name="input"></param>
    [ApiDescriptionSettings(Name = "AddColumn"), HttpPost]
    [DisplayName("增加列")]
    public void AddColumn(DbColumnInput input)
    {
        var column = new DbColumnInfo
        {
            ColumnDescription = input.ColumnDescription,
            DbColumnName = input.DbColumnName,
            IsIdentity = input.IsIdentity == 1,
            IsNullable = input.IsNullable == 1,
            IsPrimarykey = input.IsPrimarykey == 1,
            Length = input.Length,
            DecimalDigits = input.DecimalDigits,
            DataType = input.DataType
        };
        var db = _db.AsTenant().GetConnectionScope(input.ConfigId);
        db.DbMaintenance.AddColumn(input.TableName, column);
        db.DbMaintenance.AddColumnRemark(input.DbColumnName, input.TableName, input.ColumnDescription);
        if (column.IsPrimarykey)
            db.DbMaintenance.AddPrimaryKey(input.TableName, input.DbColumnName);
    }

    /// <summary>
    /// 删除列
    /// </summary>
    /// <param name="input"></param>
    [ApiDescriptionSettings(Name = "DeleteColumn"), HttpPost]
    [DisplayName("删除列")]
    public void DeleteColumn(DeleteDbColumnInput input)
    {
        var db = _db.AsTenant().GetConnectionScope(input.ConfigId);
        db.DbMaintenance.DropColumn(input.TableName, input.DbColumnName);
    }

    /// <summary>
    /// 编辑列
    /// </summary>
    /// <param name="input"></param>
    [ApiDescriptionSettings(Name = "UpdateColumn"), HttpPost]
    [DisplayName("编辑列")]
    public void UpdateColumn(UpdateDbColumnInput input)
    {
        var db = _db.AsTenant().GetConnectionScope(input.ConfigId);
        db.DbMaintenance.RenameColumn(input.TableName, input.OldColumnName, input.ColumnName);
        if (db.DbMaintenance.IsAnyColumnRemark(input.ColumnName, input.TableName))
            db.DbMaintenance.DeleteColumnRemark(input.ColumnName, input.TableName);
        db.DbMaintenance.AddColumnRemark(input.ColumnName, input.TableName, string.IsNullOrWhiteSpace(input.Description) ? input.ColumnName : input.Description);
    }

    /// <summary>
    /// 获取表列表
    /// </summary>
    /// <param name="configId">ConfigId</param>
    /// <returns></returns>
    [DisplayName("获取表列表")]
    public List<DbTableInfo> GetTableList(string configId = SqlSugarConst.MainConfigId)
    {
        var db = _db.AsTenant().GetConnectionScope(configId);
        return db.DbMaintenance.GetTableInfoList(false);
    }

    /// <summary>
    /// 增加表
    /// </summary>
    /// <param name="input"></param>
    [ApiDescriptionSettings(Name = "AddTable"), HttpPost]
    [DisplayName("增加表")]
    public void AddTable(DbTableInput input)
    {
        if (input.DbColumnInfoList == null || !input.DbColumnInfoList.Any())
            throw Oops.Oh(ErrorCodeEnum.db1000);

        if (input.DbColumnInfoList.GroupBy(q => q.DbColumnName).Any(q => q.Count() > 1))
            throw Oops.Oh(ErrorCodeEnum.db1002);

        var config = App.GetOptions<DbConnectionOptions>().ConnectionConfigs.FirstOrDefault(u => u.ConfigId == input.ConfigId);
        var db = _db.AsTenant().GetConnectionScope(input.ConfigId);
        var typeBilder = db.DynamicBuilder().CreateClass(input.TableName, new SugarTable() { TableName = input.TableName, TableDescription = input.Description });
        input.DbColumnInfoList.ForEach(m =>
        {
            var dbColumnName = config.DbSettings.EnableUnderLine ? UtilMethods.ToUnderLine(m.DbColumnName.Trim()) : m.DbColumnName.Trim();
            // 虚拟类都默认string类型，具体以列数据类型为准
            typeBilder.CreateProperty(dbColumnName, typeof(string), new SugarColumn()
            {
                IsPrimaryKey = m.IsPrimarykey == 1,
                IsIdentity = m.IsIdentity == 1,
                ColumnDataType = m.DataType,
                Length = m.Length,
                IsNullable = m.IsNullable == 1,
                DecimalDigits = m.DecimalDigits,
                ColumnDescription = m.ColumnDescription,
            });
        });
        db.CodeFirst.InitTables(typeBilder.BuilderType());
    }

    /// <summary>
    /// 删除表
    /// </summary>
    /// <param name="input"></param>
    [ApiDescriptionSettings(Name = "DeleteTable"), HttpPost]
    [DisplayName("删除表")]
    public void DeleteTable(DeleteDbTableInput input)
    {
        var db = _db.AsTenant().GetConnectionScope(input.ConfigId);
        db.DbMaintenance.DropTable(input.TableName);
    }

    /// <summary>
    /// 编辑表
    /// </summary>
    /// <param name="input"></param>
    [ApiDescriptionSettings(Name = "UpdateTable"), HttpPost]
    [DisplayName("编辑表")]
    public void UpdateTable(UpdateDbTableInput input)
    {
        var db = _db.AsTenant().GetConnectionScope(input.ConfigId);
        db.DbMaintenance.RenameTable(input.OldTableName, input.TableName);
        try
        {
            if (db.DbMaintenance.IsAnyTableRemark(input.TableName))
                db.DbMaintenance.DeleteTableRemark(input.TableName);
        }
        catch (NotSupportedException)
        {
            //Ignore 不支持该方法则不处理
        }
        db.DbMaintenance.AddTableRemark(input.TableName, input.Description);
    }

    /// <summary>
    /// 创建实体
    /// </summary>
    /// <param name="input"></param>
    [ApiDescriptionSettings(Name = "CreateEntity"), HttpPost]
    [DisplayName("创建实体")]
    public void CreateEntity(CreateEntityInput input)
    {
        var config = App.GetOptions<DbConnectionOptions>().ConnectionConfigs.FirstOrDefault(u => u.ConfigId == input.ConfigId);
        input.Position = string.IsNullOrWhiteSpace(input.Position) ? "EMC.VISITOR.Application" : input.Position;
        input.EntityName = string.IsNullOrWhiteSpace(input.EntityName) ? (config.DbSettings.EnableUnderLine ? CodeGenUtil.CamelColumnName(input.TableName, null) : input.TableName) : input.EntityName;
        string[] dbColumnNames = Array.Empty<string>();
        // 允许创建没有基类的实体
        if (!string.IsNullOrWhiteSpace(input.BaseClassName))
        {
            _codeGenOptions.EntityBaseColumn.TryGetValue(input.BaseClassName, out dbColumnNames);
            if (dbColumnNames is null || dbColumnNames is { Length: 0 })
                throw Oops.Oh("基类配置文件不存在此类型");
        }
        var templatePath = GetEntityTemplatePath();
        var targetPath = GetEntityTargetPath(input);
        var db = _db.AsTenant().GetConnectionScope(input.ConfigId);
        DbTableInfo dbTableInfo = db.DbMaintenance.GetTableInfoList(false).FirstOrDefault(m => m.Name == input.TableName || m.Name == input.TableName.ToLower()) ?? throw Oops.Oh(ErrorCodeEnum.db1001);
        List<DbColumnInfo> dbColumnInfos = db.DbMaintenance.GetColumnInfosByTableName(input.TableName, false);
        dbColumnInfos.ForEach(u =>
        {
            u.PropertyName = config.DbSettings.EnableUnderLine ? CodeGenUtil.CamelColumnName(u.DbColumnName, dbColumnNames) : u.DbColumnName; // 转下划线后的列名需要再转回来
            u.DataType = CodeGenUtil.ConvertDataType(u, config.DbType);
        });
        if (_codeGenOptions.BaseEntityNames.Contains(input.BaseClassName, StringComparer.OrdinalIgnoreCase))
            dbColumnInfos = dbColumnInfos.Where(c => !dbColumnNames.Contains(c.DbColumnName, StringComparer.OrdinalIgnoreCase)).ToList();

        var tContent = File.ReadAllText(templatePath);
        var tResult = _viewEngine.RunCompileFromCached(tContent, new
        {
            NameSpace = $"{input.Position}.Entity",
            input.TableName,
            input.EntityName,
            BaseClassName = string.IsNullOrWhiteSpace(input.BaseClassName) ? "" : $" : {input.BaseClassName}",
            input.ConfigId,
            dbTableInfo.Description,
            TableField = dbColumnInfos
        });
        File.WriteAllText(targetPath, tResult, Encoding.UTF8);
    }

    /// <summary>
    /// 单表模型更新（tableName 输入 all ,dataName 不输入值则更新所有表）
    /// 更新某个库所有表，参数如：tableName = all  ，dataName = ROBO_LOG
    /// </summary>
    /// <param name="tableName">表名：all代表全部</param>
    /// <param name="dataName">库名：指定某个库，不传值默认所有库</param>
    /// <param name="initDatabase">true:初始化数据库</param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "OneTableChange"), HttpGet]
    [DisplayName("单/多表模型更新")]
    public IActionResult OneTableChange([FromRoute] string tableName, [FromQuery] string dataName = null, [FromQuery] bool initDatabase = false)
    {
        if (tableName.IsNullOrEmptyOrNullString())
        {
            return new ContentResult
            {
                Content = "请传入正确的数据！",
                ContentType = "OK",
                StatusCode = 200,
            };
        }
        var dbOptions = App.GetOptions<DbConnectionOptions>();
        foreach (var config in dbOptions.ConnectionConfigs)
        {
            SqlSugarScopeProvider dbProvider = _db.CopyNew().GetConnectionScope(config.ConfigId);
            // 初始化/创建数据库
            if (initDatabase)
            {
                if (config.DbType != SqlSugar.DbType.Oracle)
                    dbProvider.DbMaintenance.CreateDatabase();
            }

            int count = App.EffectiveTypes.Count();
            var entityTypes = App.EffectiveTypes
            .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
                .ToList();

            if (config.ConfigId == SqlSugarConst.MainConfigId) // 默认库（有系统表特性、没有日志表和租户表特性）
                entityTypes = entityTypes.Where(
                    u => u.GetCustomAttributes<SysTableAttribute>().Any()
                || (
                             !u.GetCustomAttributes<LogTableAttribute>().Any()
                             && !u.GetCustomAttributes<TenantAttribute>().Any()
                             && !u.GetCustomAttributes<BusinessAttribute>().Any()
                    )
                    ).ToList();
            else if (config.ConfigId == SqlSugarConst.LogConfigId) // 日志库
                entityTypes = entityTypes.Where(u => u.GetCustomAttributes<LogTableAttribute>().Any()).ToList();
            else if (config.ConfigId == SqlSugarConst.MESConfigId)
                entityTypes = entityTypes.Where(u => u.GetCustomAttributes<BusinessVSAttribute>().Any()).ToList();
            else if (config.ConfigId == SqlSugarConst.WMSConfigId)
                entityTypes = entityTypes.Where(u => u.GetCustomAttributes<BusinessWmsAttribute>().Any()).ToList();
            else
                entityTypes = entityTypes.Where(u => u.GetCustomAttribute<TenantAttribute>()?.configId.ToString() == config.ConfigId).ToList(); // 自定义的库

            if (tableName.ToLower() == "all")
            {
                //全量更新表
            }
            else
            {
                entityTypes = entityTypes.Where(r => r.Name.ToLower() == tableName.ToLower()).ToList();
            }
            if (!dataName.IsNullOrEmpty())
            {
                if (!config.DbName.Trim().ToLower().Contains(dataName.Trim().ToLower()))
                {
                    continue;
                }
            }
            foreach (var entityType in entityTypes)
            {
                //dbProvider.CodeFirst.InitTablesWithAttr() //跨库codeFirst
                try
                {
                    if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
                        dbProvider.CodeFirst.InitTables(entityType);
                    else
                        dbProvider.CodeFirst.SplitTables().InitTables(entityType);


                    if (config.DbType == SqlSugar.DbType.Oracle)
                    {
                        var CodeFirst_BigStringFields = entityType.GetProperties()
                             .Where(r => r.GetCustomAttribute<SugarColumn>() != null && r.GetCustomAttribute<SugarColumn>().ColumnDataType == StaticConfig.CodeFirst_BigString)
                             .Select(r => r.Name).ToList();

                        if (CodeFirst_BigStringFields.Count > 0)
                        {
                            string entityName = entityType.Name;
                            var sugarTable = entityType.GetCustomAttribute<SugarTable>();
                            if (sugarTable != null && !sugarTable.TableName.IsNullOrEmpty())
                                entityName = sugarTable.TableName;

                            foreach (var fieldName in CodeFirst_BigStringFields)
                            {
                                try
                                {
                                    string deleteColumn = $"ALTER TABLE {config.TableSettings.TablePrefix}{entityName}{config.TableSettings.TableSuffix} DROP COLUMN {fieldName}";
                                    dbProvider.Ado.ExecuteCommand(deleteColumn);
                                }
                                catch (Exception ex) { }
                                try
                                {
                                    string addTempColumn = $"ALTER TABLE {config.TableSettings.TablePrefix}{entityName}{config.TableSettings.TableSuffix} ADD ({fieldName}1 CLOB)";
                                    dbProvider.Ado.ExecuteCommand(addTempColumn);
                                }
                                catch (Exception ex) { }
                                try
                                {
                                    string updateToOrgColumn = $"ALTER TABLE {config.TableSettings.TablePrefix}{entityName}{config.TableSettings.TableSuffix} RENAME COLUMN {fieldName}1 TO {fieldName}";
                                    dbProvider.Ado.ExecuteCommand(updateToOrgColumn);
                                }
                                catch (Exception ex)
                                {

                                }


                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                }
            }
        };

        return new ContentResult
        {
            Content = "更新完毕！",
            ContentType = "OK",
            StatusCode = 200,
        };
    }

    /// <summary>
    /// 生成系统种子数据
    /// </summary>
    [HttpGet]
    [AllowAnonymous]
    public IActionResult OneTimeInitSystemSeedData(string seedDataTypeName = "ALL")
    {
        var dbOptions = App.GetOptions<DbConnectionOptions>();
        foreach (var config in dbOptions.ConnectionConfigs)
        {
            SqlSugarScopeProvider dbProvider = _db.CopyNew().GetConnectionScope(config.ConfigId);
            int count = App.EffectiveTypes.Count();
            var entityTypes = App.EffectiveTypes
            .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
                .ToList();

            if (config.ConfigId == SqlSugarConst.MainConfigId) // 默认库（有系统表特性、没有日志表和租户表特性）
                entityTypes = entityTypes.Where(
                    u => u.GetCustomAttributes<SysTableAttribute>().Any()
                || (
                             !u.GetCustomAttributes<LogTableAttribute>().Any()
                             && !u.GetCustomAttributes<TenantAttribute>().Any()
                             && !u.GetCustomAttributes<BusinessAttribute>().Any()
                    )
                    ).ToList();
            else if (config.ConfigId == SqlSugarConst.LogConfigId) // 日志库
                entityTypes = entityTypes.Where(u => u.GetCustomAttributes<LogTableAttribute>().Any()).ToList();
            else if (config.ConfigId == SqlSugarConst.MESConfigId)
                entityTypes = entityTypes.Where(u => u.GetCustomAttributes<BusinessVSAttribute>().Any()).ToList();
            else if (config.ConfigId == SqlSugarConst.WMSConfigId)
                entityTypes = entityTypes.Where(u => u.GetCustomAttributes<BusinessWmsAttribute>().Any()).ToList();
            else
                entityTypes = entityTypes.Where(u => u.GetCustomAttribute<TenantAttribute>()?.configId.ToString() == config.ConfigId).ToList(); // 自定义的库

            // 初始化种子数据

            var seedDataTypes = App.EffectiveTypes.Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.GetInterfaces().Any(i => i.HasImplementedRawGeneric(typeof(ISqlSugarEntitySeedData<>))))
                .WhereIF(config.SeedSettings.EnableIncreSeed, u => u.IsDefined(typeof(IncreSeedAttribute), false)).ToList();

            if (!seedDataTypeName.IsNullOrEmpty() && seedDataTypeName.ToUpper() != "ALL")
                seedDataTypes = seedDataTypes.Where(r => r.Name.ToUpper() == seedDataTypeName.Trim().ToUpper()).ToList();

            foreach (var seedType in seedDataTypes)
            {
                var entityType = seedType.GetInterfaces().First().GetGenericArguments().First();
                if (config.ConfigId == SqlSugarConst.MainConfigId) // 默认库（有系统表特性、没有日志表和租户表特性）
                {
                    if (entityType.GetCustomAttribute<SysTableAttribute>() == null && (entityType.GetCustomAttribute<LogTableAttribute>() != null || entityType.GetCustomAttribute<TenantAttribute>() != null))
                        continue;
                }
                else if (config.ConfigId == SqlSugarConst.LogConfigId) // 日志库
                {
                    if (entityType.GetCustomAttribute<LogTableAttribute>() == null)
                        continue;
                }
                else if (config.ConfigId == SqlSugarConst.MESConfigId)
                {
                    if (entityType.GetCustomAttribute<BusinessVSAttribute>() == null)
                        continue;
                }
                else if (config.ConfigId == SqlSugarConst.WMSConfigId)
                {
                    if (entityType.GetCustomAttribute<BusinessWmsAttribute>() == null)
                        continue;
                }
                else
                {
                    var att = entityType.GetCustomAttribute<TenantAttribute>(); // 自定义的库
                    if (att == null || att.configId.ToString() != config.ConfigId) continue;
                }

                var instance = Activator.CreateInstance(seedType);
                var hasDataMethod = seedType.GetMethod("HasData");
                var seedData = ((IEnumerable)hasDataMethod?.Invoke(instance, null))?.Cast<object>();
                if (seedData == null) continue;

                var entityInfo = dbProvider.EntityMaintenance.GetEntityInfo(entityType);
                //if (entityInfo.DbTableName.Contains(nameof(SysMenu)))
                //    continue;
                if (entityInfo.Columns.Any(u => u.IsPrimarykey))
                {
                    // 按主键进行批量增加和更新
                    var storage = dbProvider.StorageableByObject(seedData.ToList()).ToStorage();
                    storage.AsInsertable.ExecuteCommand();
                    storage.AsUpdateable.ExecuteCommand();
                }
                else
                {
                    // 无主键则只进行插入
                    if (!dbProvider.Queryable(entityInfo.DbTableName, entityInfo.DbTableName).Any())
                        dbProvider.InsertableByObject(seedData.ToList()).ExecuteCommand();
                }
            }
        };

        return new ContentResult
        {
            Content = "更新完毕！",
            ContentType = "OK",
            StatusCode = 200,
        };
    }


    #region 2024-09-14 删除，数据迁移请查看类SysDataTransferOverrideService.cs
    ///// <summary>
    ///// 不同库数据迁移复制(会自动更新目标表结构)
    ///// </summary>
    ///// <param name="tableName">需要同步的表/all表示整个库</param>
    ///// <param name="clearTargetTable">是否清空目标表</param>
    ///// <param name="dataName">需要同步的库名(源数据库)</param>
    ///// <param name="initDatabase">true:初始化目标数据库(源数据库) ，默认不初始化</param>
    ///// <returns></returns>
    //[DisplayName("不同库数据迁移复制(会自动更新目标表结构)")]
    //public async Task<IActionResult> DataBaseCopy([FromRoute] string tableName, [FromQuery] bool clearTargetTable = false, [FromQuery] string dataName = null, [FromQuery] bool initDatabase = false)
    //{
    //    StringBuilder sb = new StringBuilder();
    //    if (tableName.IsNullOrEmptyOrNullString())
    //    {
    //        return new ContentResult
    //        {
    //            Content = "请传入正确的数据！",
    //            ContentType = "OK",
    //            StatusCode = 200,
    //        };
    //    }
    //    var dbOptions = App.GetOptions<DbConnectionOptions>();

    //    foreach (var config in dbOptions.ConnectionConfigs)
    //    {
    //        SqlSugarScopeProvider dbProvider = _db.CopyNew().GetConnectionScope(config.ConfigId);


    //        int count = App.EffectiveTypes.Count();
    //        var entityTypes = App.EffectiveTypes
    //        .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
    //            .ToList();

    //        if (config.ConfigId == SqlSugarConst.MainConfigId) // 默认库（有系统表特性、没有日志表和租户表特性）
    //            entityTypes = entityTypes.Where(
    //                u => u.GetCustomAttributes<SysTableAttribute>().Any()
    //            || (
    //                         !u.GetCustomAttributes<LogTableAttribute>().Any()
    //                         && !u.GetCustomAttributes<TenantAttribute>().Any()
    //                         && !u.GetCustomAttributes<BusinessAttribute>().Any()
    //                )
    //                ).ToList();
    //        else if (config.ConfigId == SqlSugarConst.LogConfigId) // 日志库
    //            entityTypes = entityTypes.Where(u => u.GetCustomAttributes<LogTableAttribute>().Any()).ToList();
    //        else if (config.ConfigId == SqlSugarConst.MESConfigId)
    //            entityTypes = entityTypes.Where(u => u.GetCustomAttributes<BusinessVSAttribute>().Any()).ToList();
    //        else if (config.ConfigId == SqlSugarConst.WMSConfigId)
    //            entityTypes = entityTypes.Where(u => u.GetCustomAttributes<BusinessWmsAttribute>().Any()).ToList();
    //        else
    //            entityTypes = entityTypes.Where(u => u.GetCustomAttribute<TenantAttribute>()?.configId.ToString() == config.ConfigId).ToList(); // 自定义的库

    //        SqlSugarScopeProvider dbProviderMAINTransfer = null, dbProviderMESTransfer = null, dbProviderWMSTransfer = null;
    //        try
    //        {
    //            dbProviderMAINTransfer = _db.CopyNew().GetConnectionScope(SqlSugarConst.MainConfigIdTransfer);
    //            dbProviderMESTransfer = _db.CopyNew().GetConnectionScope(SqlSugarConst.MESConfigIdTransfer);
    //            dbProviderWMSTransfer = _db.CopyNew().GetConnectionScope(SqlSugarConst.WMSConfigIdTransfer);

    //            // 初始化/创建数据库
    //            if (initDatabase)
    //            {
    //                if (config.DbType != SqlSugar.DbType.Oracle)
    //                    dbProviderMAINTransfer.DbMaintenance.CreateDatabase();
    //                if (config.DbType != SqlSugar.DbType.Oracle)
    //                    dbProviderMESTransfer.DbMaintenance.CreateDatabase();
    //                if (config.DbType != SqlSugar.DbType.Oracle)
    //                    dbProviderWMSTransfer.DbMaintenance.CreateDatabase();
    //            }


    //        }
    //        catch (Exception ex) { }
    //        if (tableName.ToLower() == "all")
    //        {
    //            //全量
    //        }
    //        else
    //        {
    //            entityTypes = entityTypes.Where(r => r.Name.ToLower() == tableName.ToLower()).ToList();
    //        }
    //        if (!dataName.IsNullOrEmpty())
    //        {
    //            if (!config.DbName.Trim().ToLower().Contains(dataName.Trim().ToLower()))
    //            {
    //                continue;
    //            }
    //        }
    //        foreach (var entityType in entityTypes.Where(r => r.GetCustomAttribute<SqlLiteNotMapperTableUpdateAttribute>() == null))
    //        {
    //            try
    //            {
    //                if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
    //                {
    //                    switch (config.ConfigId)
    //                    {
    //                        case SqlSugarConst.MainConfigId:
    //                            dbProviderMAINTransfer.CodeFirst.InitTables(entityType);
    //                            break;
    //                        case SqlSugarConst.MESConfigId:
    //                            dbProviderMESTransfer.CodeFirst.InitTables(entityType);
    //                            break;
    //                        case SqlSugarConst.WMSConfigId:
    //                            dbProviderWMSTransfer.CodeFirst.InitTables(entityType);
    //                            //await dbProviderWMSTransfer.Insertable(dataList).ExecuteCommandAsync();
    //                            break;
    //                        default:
    //                            break;
    //                    }
    //                }
    //            }
    //            catch (Exception ex)
    //            {
    //                sb.AppendLine(ex.ToString());
    //            }
    //        }
    //        foreach (var entityType in entityTypes)
    //        {
    //            if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
    //            {
    //                string entityTypeName = entityType.Name;
    //                var table = entityType.GetCustomAttribute<SugarTable>();
    //                if (table != null && !table.TableName.IsNullOrEmpty())
    //                    entityTypeName = table.TableName;

    //                try
    //                {
    //                    var dataList = await dbProvider.QueryableByObject(entityType).ToListAsync();
    //                    int dataCount = 0;
    //                    ICollection col = dataList as ICollection;
    //                    if (col != null)
    //                    {
    //                        dataCount = col.Count;
    //                    }
    //                    switch (config.ConfigId)
    //                    {
    //                        case SqlSugarConst.MainConfigId:
    //                            if (clearTargetTable && dataCount > 0)
    //                                await dbProviderMAINTransfer.Deleteable<object>().AS(entityTypeName).ExecuteCommandAsync();
    //                            if (dataList != null && dataCount > 0)
    //                                await dbProviderMAINTransfer.InsertableByObject(dataList).ExecuteCommandAsync();
    //                            break;
    //                        case SqlSugarConst.MESConfigId:
    //                            if (clearTargetTable && dataCount > 0)
    //                                await dbProviderMESTransfer.Deleteable<object>().AS(entityTypeName).ExecuteCommandAsync();
    //                            if (dataList != null && dataCount > 0)
    //                                await dbProviderMESTransfer.InsertableByObject(dataList).ExecuteCommandAsync();
    //                            break;
    //                        case SqlSugarConst.WMSConfigId:
    //                            if (clearTargetTable && dataCount > 0)
    //                                await dbProviderWMSTransfer.Deleteable<object>().AS(entityTypeName).ExecuteCommandAsync();
    //                            if (dataList != null && dataCount > 0)
    //                                await dbProviderWMSTransfer.InsertableByObject(dataList).ExecuteCommandAsync();
    //                            break;
    //                        default:
    //                            break;
    //                    }
    //                }
    //                catch (Exception ex)
    //                {
    //                    sb.AppendLine(ex.ToString());
    //                }
    //            }
    //        }
    //    }
    //    MyLogHelper.AddLog(sb.ToString(), "不同库数据迁移复制", null);
    //    return new ContentResult
    //    {
    //        Content = sb.ToString(),
    //        ContentType = "OK",
    //        StatusCode = 200,
    //    };
    //}
    ///// <summary>
    ///// 获取实体模板文件路径
    ///// </summary>
    ///// <returns></returns> 
    #endregion

    /// <summary>
    /// Web初始化，将Web中的一些内容重命名
    /// </summary>
    [HttpGet]
    public void OneTimeInitWebReplaceString()
    {
        var webPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName, "EMC.VISITOR.ZFrontend", "EMC.VISITOR.Vue3.Web");
        GetFilesInFolder(webPath,
            new string[] 
            { 
            "src\\views\\system\\otherSystemMapperGen\\index.vue",
            "src\\views\\system\\codeGen\\index.vue",
            "src\\layout\\footer\\index.vue",
            "genEntity.vue",
            },
            new string[] { "themeConfig.ts", "print-data.ts", "providers.ts","index.html","README.md" },
            new string[] { "node_modules", "dist" }
           );
    }
   

    /// <summary>
    /// 递归查询文件及文件下的子文件
    /// </summary>
    /// <param name="folderPath">需要查询的根文件</param>
    /// <param name="readFilePathNames">需要读的文件路径+名称</param>
    /// <param name="readFileNames">需要读的文件名</param>
    /// <param name="excludeFolderNames">需要排除的文件夹名称</param>
    private void GetFilesInFolder(string folderPath, string[] readFilePathNames, string[] readFileNames, string[] excludeFolderNames)
    {
        try
        {
            //"index.vue" ".ts"  "Robotec.NET.Application"  'Robotec'
            // 获取当前文件夹下的所有文件
            string[] files = Directory.GetFiles(folderPath);
            if (files != null)
                files = files.Where(r => readFilePathNames.Where(fileP => r.EndsWith(fileP)).Any() || readFileNames.Contains(Path.GetFileName(r))).ToArray();

            var name= "EMC.VISITOR".Split('.')[0];
            foreach (string file in files)
            {
                var readString = FileHelper.ReadFile(file, Encoding.UTF8);
                if (readString.Contains("Robotec") || readString.Contains("Robotec.NET.Application") || readString.Contains("Robotec.Core"))
                {
                    readString = readString
                        .Replace("Robotec.NET.Application", "EMC.VISITOR.Application")
                        .Replace("Robotec.Core", "EMC.VISITOR.Core")
                        .Replace("Robotec", name);
                     
                    FileHelper.WriteFile(file, readString, Encoding.UTF8, true);
                    Console.WriteLine($"文件: {file}初始化完成......");
                }
            }

            // 获取当前文件夹下的所有子文件夹
            string[] subFolders = Directory.GetDirectories(folderPath);
            foreach (string subFolder in subFolders)
            {
                if (excludeFolderNames.Contains(subFolder))
                    continue;

                // 递归调用以处理子文件夹
                GetFilesInFolder(subFolder, readFilePathNames, readFileNames, excludeFolderNames);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}");
        }
    }


    private static string GetEntityTemplatePath()
    {
        var templatePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "Template");
        return Path.Combine(templatePath, "Entity.cs.vm");
    }

    /// <summary>
    /// 设置生成实体文件路径
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    private static string GetEntityTargetPath(CreateEntityInput input)
    {
        var backendPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName, input.Position, "Entity");
        if (!Directory.Exists(backendPath))
            Directory.CreateDirectory(backendPath);
        return Path.Combine(backendPath, input.EntityName + ".cs");
    }
}